package com.linkage.jz.bankruptcy.activity.Project.ZQUser;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.base.BaseActivity;
import com.linkage.jz.bankruptcy.bean.SerializedZQApplyFileList;
import com.linkage.jz.bankruptcy.bean.ZQApplyDraft;
import com.linkage.jz.bankruptcy.bean.ZQBaseProjectCrDecInfo;
import com.linkage.jz.bankruptcy.net.BaseResponse;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.utils.EditTextChangedListenerAdapter;
import com.linkage.seapeak.activity.project.ExamineAdvActivity;
import com.linkage.seapeak.utils.CommonUtils;
import com.linkage.seapeak.view.QuickPopView;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * A login screen that offers login via email/password.
 */
public class CreateZQFristApplyActivity extends BaseActivity implements OnClickListener, ZQApplyView {
    private static final String TAG = CreateZQFristApplyActivity.class.getSimpleName();
    public static final String KEY_CREDITORID = "KEY_CREDITORID";
    public static final String KEY_PROJECTID = "KEY_PROJECTID";
    private static final String KEY_BIGTYPE = "KEY_BIGTYPE";
    public static final String KEY_TYPE = "KEY_TYPE";
    public static final String KEY_EDITING = "KEY_EDITING";
    public static final String KEY_CREDITOR_RIGHTS_ID = "KEY_CREDITOR_RIGHTS_ID";
    public static final String KEY_EDITING_FILE_LISTS = "KEY_EDITING_FILE_LISTS";

    /**
     *  @param context 上下文
     * @param creditorId 债权人ID
     * @param projectId 项目Id
     * @param bigtype // 0表示企业，1表示自然债权人，2标识税务机关
     * @param type 0:管理人; 1:债权人
     */
    public static void start(Context context, String creditorId, String projectId, String bigtype, int type) {
        Intent intent = new Intent(context, CreateZQFristApplyActivity.class);
        intent.putExtra(KEY_CREDITORID, creditorId);
        intent.putExtra(KEY_PROJECTID, projectId);
        intent.putExtra(KEY_BIGTYPE, bigtype);
        intent.putExtra(KEY_TYPE, type);
        context.startActivity(intent);
    }

    EditText base_money, base_interest_money, base_other_money;
    Button top_back;
    TextView top_mune1, top_mune2, base_tatal_money;

    private TextView popClick;

    private EditText interestDescEt, remarkLeftToAdminDescEt;
    private boolean isModifeied = false;
    private CheckBox hasPriorityCb, hasNotPriorityCb;
    private LinearLayout hasPriorityLayout;
    private EditText priorityBaseMoneyEt, priorityInterestEt, priorityDescEt, rightDescEt;

    private ZQBaseProjectCrDecInfo mEditInfo;
    private String mBigType;
    private int mType;
    private String mCreditorId;
    private String mProjectId;
    private String mCreditorRightsId;
    private TempSavePresenter mTempSavePresenter;
    private SerializedZQApplyFileList mSerializedZQApplyFileLists;

    private EditTextChangedListenerAdapter editTextChangedListenerAdapter = new EditTextChangedListenerAdapter() {
        @Override
        public void afterTextChanged(Editable editable) {
            isModifeied = true;
            calcTotal();
        }
    };

    private View.OnFocusChangeListener calTotalListener = (view, b) -> {
        if (!b && view instanceof EditText) validatesInput((EditText) view);
        calcTotal();
    };

    private View.OnFocusChangeListener validatesInputListener = (view, b) -> {
        if (!b && view instanceof EditText) validatesInput((EditText) view);
    };

    private CompoundButton.OnCheckedChangeListener checkedChangeListener = new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            if (!b) return;
            isModifeied = true;
            if (compoundButton == hasPriorityCb) {
                hasPriorityLayout.setVisibility(View.VISIBLE);
                hasNotPriorityCb.setChecked(false);
                hasNotPriorityCb.setEnabled(true);
                hasPriorityCb.setEnabled(false);
            } else if (compoundButton == hasNotPriorityCb) {
                hasPriorityLayout.setVisibility(View.GONE);
                hasPriorityCb.setChecked(false);
                hasPriorityCb.setEnabled(true);
                hasNotPriorityCb.setEnabled(false);
            }
        }

    };





    @Override
    public void initData() {

    }

    @Override
    public void setListener() {
        top_back.setOnClickListener(this);
        top_mune1.setOnClickListener(this);
        top_mune2.setOnClickListener(this);
    }

    @Override
    public void initTitle() {
        ((TextView) findViewById(R.id.top_title)).setText("申报债权");
    }

    @Override
    public void initView() {
        top_back = findViewById(R.id.top_back);
        top_mune1 = findViewById(R.id.top_mune1);
        top_mune2 = findViewById(R.id.top_mune2);

        base_tatal_money = findViewById(R.id.base_tatal_money);
        base_money = findViewById(R.id.base_money);
        base_interest_money = findViewById(R.id.base_interest_money);
        base_other_money = findViewById(R.id.base_other_money);
        interestDescEt = findViewById(R.id.interest_desc);
        remarkLeftToAdminDescEt = findViewById(R.id.remark_left_to_admin_desc);
        hasPriorityCb = findViewById(R.id.ck_priority);
        hasNotPriorityCb = findViewById(R.id.ck_priority_not);
        hasPriorityLayout = findViewById(R.id.ck_has_priority_layout);

        priorityBaseMoneyEt = findViewById(R.id.priority_base_money);
        priorityInterestEt = findViewById(R.id.priority_interest_money);
        priorityDescEt = findViewById(R.id.priority_desc);
        rightDescEt = findViewById(R.id.right_desc_et);

        popClick = findViewById(R.id.pop_click);
        /**
         * 弹窗
         */
        popClick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                QuickPopView.show(CreateZQFristApplyActivity.this);
            }
        });

        // 0表示企业债权人，1表示自然债权人，2标识税务机关债权人
        switch (mBigType) {
            case "2":
                findViewById(R.id.creditor_type_layout).setVisibility(View.GONE);
                ((TextView) findViewById(R.id.tv0)).setText("正税:");
                ((TextView) findViewById(R.id.tv1)).setText("滞纳金:");
                findViewById(R.id.interest_desc_layout).setVisibility(View.GONE);
                base_other_money.setHint("0.00");
                break;
            case "0":
            case "1":
            default:
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_create_zq_frist_apply);
        mBigType = getIntent().getStringExtra(KEY_BIGTYPE);
        if (mBigType == null) mBigType = "0";
        mType = getIntent().getIntExtra(KEY_TYPE, 0);
        mCreditorId = getIntent().getStringExtra(KEY_CREDITORID);
        mProjectId = getIntent().getStringExtra(KEY_PROJECTID);
        super.onCreate(savedInstanceState);
        fetchinfo();
    }

    private void fetchinfo() {
        mShapeLoadingDialog.setLoadingText("获取暂存信息中...");
        mShapeLoadingDialog.getDialog().setCancelable(false);
        mShapeLoadingDialog.setCanceledOnTouchOutside(false);
        mShapeLoadingDialog.show();

        Network.getAPIService().getZQApplyDraft(getUserToken(),
                mProjectId,
                mType,
                mCreditorId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<BaseResponse<ZQApplyDraft>>() {
                    @Override
                    public void onNext(BaseResponse<ZQApplyDraft> zqApplyinfoBaseResponse) {
                        mShapeLoadingDialog.dismiss();
                        if (zqApplyinfoBaseResponse.getCode() == 0) {
                            super.onNext(zqApplyinfoBaseResponse);
                            ZQApplyDraft draft = zqApplyinfoBaseResponse.getData();
                            if (draft != null) {
                                ZQBaseProjectCrDecInfo zqBaseProjectCrDecInfo = draft.getProjectCrDecTemp();
                                //添加mCreditorRightsId
                                if (draft.getProjectCrDecTemp() == null) {
                                    initBlankDraft();
                                    return;
                                }
                                mCreditorRightsId = draft.getProjectCrDecTemp().getId();
                                if (zqBaseProjectCrDecInfo != null) {
                                    new AlertDialog.Builder(CreateZQFristApplyActivity.this)
                                            .setTitle("提示")
                                            .setMessage("您有未完成提交的债权申报信息，\n是否继续未完成的操作？")
                                            .setCancelable(false)
                                            .setPositiveButton("继续", (dialogInterface, i) -> {
                                                fillWithinfo(zqBaseProjectCrDecInfo);
                                                mEditInfo = zqBaseProjectCrDecInfo;
                                                initListener();
                                                mSerializedZQApplyFileLists = new SerializedZQApplyFileList(mEditInfo);
                                                mTempSavePresenter = new TempSavePresenter(CreateZQFristApplyActivity.this,
                                                        mShapeLoadingDialog, mProjectId, mCreditorId, mType, mCreditorRightsId,
                                                        mEditInfo, mSerializedZQApplyFileLists);
                                            })
                                            .setNegativeButton("重新填报", (dialogInterface, i) -> {
                                                initBlankDraft();
                                                isModifeied = true;
                                            })
                                            .show();
                                } else initBlankDraft();
                            } else initBlankDraft();
                        } else initBlankDraft();
                    }

                    private void initBlankDraft() {
                        initListener();
                        mEditInfo = new ZQBaseProjectCrDecInfo();
                        mSerializedZQApplyFileLists = new SerializedZQApplyFileList(mEditInfo);
                        mTempSavePresenter = new TempSavePresenter(CreateZQFristApplyActivity.this,
                                mShapeLoadingDialog, mProjectId, mCreditorId, mType, mCreditorRightsId,
                                mEditInfo, mSerializedZQApplyFileLists);
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mShapeLoadingDialog.dismiss();
                        super.onError(e);
                        finish();
                    }
                });
    }

    private void fillWithinfo(@NonNull ZQBaseProjectCrDecInfo info) {
        if (mBigType.equals("2")) {
            if (info.getDeclareAmountRegularTax() != null) base_money.setText(info.getDeclareAmountRegularTax());
            if (info.getDeclareAmountOverdueFine() != null) base_interest_money.setText(info.getDeclareAmountOverdueFine());
        }
        else {
            if (info.getDeclareAmountPrincipal() != null) base_money.setText(info.getDeclareAmountPrincipal());
            if (info.getDeclareAmountInterest() != null) base_interest_money.setText(info.getDeclareAmountInterest());
        }
        if (info.getDeclareAmountOther() != null) base_other_money.setText(info.getDeclareAmountOther());
        calcTotal();
        if (info.getDeclareAmountInterestDetail() != null) interestDescEt.setText(info.getDeclareAmountInterestDetail());
        if (info.getDeclareAmountOtherDetail() != null)
            remarkLeftToAdminDescEt.setText(info.getDeclareAmountOtherDetail());
        if (info.getPreferredCreditorRights().equals("true")) { //todo
            hasPriorityLayout.setVisibility(View.VISIBLE);
            hasNotPriorityCb.setChecked(false);
            hasNotPriorityCb.setEnabled(true);
            hasPriorityCb.setChecked(true);
            hasPriorityCb.setEnabled(false);
        } else {
            hasPriorityLayout.setVisibility(View.GONE);
            hasPriorityCb.setChecked(false);
            hasPriorityCb.setEnabled(true);
            hasNotPriorityCb.setChecked(true);
            hasNotPriorityCb.setEnabled(false);
        }
        if (info.getGuaranteePriority() != null)
            priorityBaseMoneyEt.setText(info.getGuaranteePriority());
        if (info.getOtherPriority() != null)
            priorityInterestEt.setText(info.getOtherPriority());
        if (info.getPreferredCreditorRightsDetail() != null) priorityDescEt.setText(info.getPreferredCreditorRightsDetail());

        if(info.getCreditorRightsNote()!=null)
            rightDescEt.setText(info.getCreditorRightsNote());
    }

    private void initListener() {

        base_money.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                isModifeied = true;
                calcTotal();
            }
            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        base_interest_money.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                isModifeied = true;
                calcTotal();
            }
            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        base_other_money.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                isModifeied = true;
                calcTotal();
            }
            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        interestDescEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                isModifeied = true;
                calcTotal();
            }
            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        remarkLeftToAdminDescEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                isModifeied = true;
                calcTotal();
            }
            @Override
            public void afterTextChanged(Editable editable) {

            }
        });


        priorityBaseMoneyEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                isModifeied = true;
                calcTotal();
            }
            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        priorityInterestEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                isModifeied = true;
                calcTotal();
            }
            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        priorityDescEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                isModifeied = true;
                calcTotal();
            }
            @Override
            public void afterTextChanged(Editable editable) {

            }
        });



        base_money.setOnFocusChangeListener(calTotalListener);
        base_interest_money.setOnFocusChangeListener(calTotalListener);
        base_other_money.setOnFocusChangeListener(calTotalListener);
        priorityBaseMoneyEt.setOnFocusChangeListener(validatesInputListener);
        priorityInterestEt.setOnFocusChangeListener(validatesInputListener);

        hasPriorityCb.setOnCheckedChangeListener(checkedChangeListener);
        hasNotPriorityCb.setOnCheckedChangeListener(checkedChangeListener);

    }

    private void validatesInput(EditText editText) {
        Editable input = editText.getText();
        int index = input.toString().indexOf(".");
        if (index < 0) {
            if (input.length() != 0) input.append(".00");
        } else if (index < input.length() - 3) {
            input.delete(index + 3, input.length());
        } else if (index == input.length() - 1) {
            if (input.length() == 1) input.insert(0, "0");
            input.append("00");
        } else if (index == input.length() - 2) {
            input.append("0");
        }
    }

    private void calcTotal() {
        String str_base_money = base_money.getText().toString();
        String str_base_interest_money = base_interest_money.getText().toString();
        String str_base_other_money = base_other_money.getText().toString();
        double double_base_money = 0.00;
        double double_base_interest_money = 0.00;
        double double_base_other_money = 0.00;
        try {
            double_base_money = Double.parseDouble(str_base_money);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        try {
            double_base_interest_money = Double.parseDouble(str_base_interest_money);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        try {
            double_base_other_money = Double.parseDouble(str_base_other_money);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        double total = double_base_money + double_base_interest_money + double_base_other_money;
        if (total > 0) base_tatal_money.setText(CommonUtils.resetMoney_nodot(String.valueOf(total)));
        else base_tatal_money.setText("0.00");
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.top_back:
                onBackPressed();
                break;
            case R.id.top_mune1:
                //下一步
                if(!checkMoney())
                {
                    return;
                }
                calcTotal();
                if (checkAmountValidate()) {
                    syncEdit();
                    CreateZQFristApplyTwoActivity.start(this, mCreditorId, mProjectId, mType, mEditInfo, mSerializedZQApplyFileLists, mCreditorRightsId,mEditInfo);
                    finish();
                }
                break;
            case R.id.top_mune2:
                //暂存
                syncEdit();
                mTempSavePresenter.tempSave();
                break;
        }
    }

    @Override
    public void onBackPressed() {
        calTotalListener.onFocusChange(getCurrentFocus(), false);
        top_back.requestFocus();
        if (isModifeied) mTempSavePresenter.onBackPressed();
        else super.onBackPressed();
    }

    @Override
    public void syncEdit() {
        Editable editable;
        editable = base_money.getText();
        if (editable.length() > 0) {
            if ("2".equals(mBigType)) mEditInfo.setDeclareAmountRegularTax(editable.toString());
            else mEditInfo.setDeclareAmountPrincipal(editable.toString());
        }
        else {
            Toast.makeText(this, "请填写申报金额", Toast.LENGTH_SHORT).show();
            return;
        }
        editable = base_interest_money.getText();
        if ("2".equals(mBigType)) {
            if (editable.length() > 0) mEditInfo.setDeclareAmountOverdueFine(editable.toString());
        }
        else if (editable.length() > 0) mEditInfo.setDeclareAmountInterest(editable.toString());
        editable = base_other_money.getText();
        if (editable.length() > 0) mEditInfo.setDeclareAmountOther(editable.toString());
        editable = interestDescEt.getText();
        if (editable.length() > 0) mEditInfo.setDeclareAmountInterestDetail(editable.toString());
        editable = remarkLeftToAdminDescEt.getText();
        if (editable.length() > 0) mEditInfo.setDeclareAmountOtherDetail(editable.toString());
        mEditInfo.setPreferredCreditorRights(hasPriorityCb.isChecked() ? "true" : "false");
        mEditInfo.setDeclareAmountTotal(base_tatal_money.getText().toString());

        editable = priorityBaseMoneyEt.getText();
        if (editable.length() > 0) mEditInfo.setGuaranteePriority(editable.toString());
        editable = priorityInterestEt.getText();
        if (editable.length() > 0) mEditInfo.setOtherPriority(editable.toString());
        editable = priorityDescEt.getText();
        if (editable.length() > 0) mEditInfo.setPreferredCreditorRightsDetail(editable.toString());
        editable = rightDescEt.getText();
        if (editable.length() > 0) mEditInfo.setCreditorRightsNote(editable.toString());
    }

    @Override
    public String getUserToken() {
        return super.getUserToken();
    }

    @Override
    public Context getContext() {
        return this;
    }

    private boolean checkMoney() {
        String str_base_money = base_money.getText().toString();
        String str_base_interest_money = base_interest_money.getText().toString();
        String str_base_other_money = base_other_money.getText().toString();
        String str_priorityBaseMoneyEt  = priorityBaseMoneyEt.getText().toString();
        String str_priorityInterestEt  = priorityInterestEt.getText().toString();
        if(!CommonUtils.vailMoney(CreateZQFristApplyActivity.this,str_base_money)) {
            return  false;
        }
        if(!CommonUtils.vailMoney(CreateZQFristApplyActivity.this,str_base_interest_money)) {
            return  false;
        }
        if(!CommonUtils.vailMoney(CreateZQFristApplyActivity.this,str_base_other_money)) {
            return  false;
        }
//        if(!CommonUtils.vailMoney(CreateZQFristApplyActivity.this,str_priorityInterestEt)) {
//            return  false;
//        }
//
//        if(!CommonUtils.vailMoney(CreateZQFristApplyActivity.this,str_priorityBaseMoneyEt)) {
//            return  false;
//        }

        return true;
    }
    private boolean checkAmountValidate() {
        boolean validate = !base_tatal_money.getText().equals("0.00");
        if (!validate) Toast.makeText(this, "请填写申报金额", Toast.LENGTH_SHORT).show();
        return validate;
    }

}

